package com.dzl.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.dzl.admin.dao.SysAdminMapper;
import com.dzl.admin.pojo.SysAdmin;
import com.dzl.admin.pojo.SysMenu;
import com.dzl.admin.pojo.SysRole;
import com.dzl.admin.pojo.SysRoleMenu;
import com.dzl.admin.pojo.query.SysAdminQuery;
import com.dzl.admin.pojo.vo.LoginSysAdminVo;
import com.dzl.admin.pojo.vo.SysAdminVo;
import com.dzl.admin.service.SysAdminService;
import com.dzl.admin.service.SysMenuService;
import com.dzl.admin.service.SysRoleMenuService;
import com.dzl.admin.service.SysRoleService;
import com.dzl.base.service.BaseServiceImpl;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.enterprise.pojo.WelfareEnterprise;
import com.dzl.enterprise.service.WelfareEnterpriseService;
import com.dzl.supplier.pojo.WelfareSupplier;
import com.dzl.supplier.pojo.vo.WelfareSupplierLoginVo;
import com.dzl.util.EmptyUtils;
import com.dzl.util.PasswordUtil;
import com.dzl.util.RedisUtil;
import com.dzl.util.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 企服服务端用户表(SysAdmin)表服务实现类
 * @author caobucao
 * @since 2021-05-13 15:35:49
 */
@Service("sysAdminService")
public class SysAdminServiceImpl extends BaseServiceImpl<SysAdmin> implements SysAdminService {

    @Autowired
    private SysAdminMapper sysAdminMapper;
    @Autowired
    private WelfareEnterpriseService welfareEnterpriseService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public Map loginVerifyPhone(String phone) {
        SysAdmin query = new SysAdmin();
        //query.setEnterpriseId(welfareEnterprise.getId());
        query.setPhone(phone);
        query.setStatus(CommonConstants.YES);
        query.setType(CommonConstants.SYS_ADMIN_TYPE.APP);
        List<SysAdmin> sysAdmins = sysAdminMapper.select(query);
        SysAdmin sysAdmin = EmptyUtils.isNotEmpty(sysAdmins)?sysAdmins.get(0):null;
        if(EmptyUtils.isEmpty(sysAdmin)) {
            throw new CommonException("账号不存在！");
        }
        if(sysAdmin.getUserStatus()==0||sysAdmin.getStatus()==0) {
            throw new CommonException("账号已停用");
        }
        Map result = Maps.newHashMapWithExpectedSize(2);
        result.put("userId",sysAdmin.getId());
        result.put("password", EmptyUtils.isNotEmpty(sysAdmin.getPassword())?"yes":"");
        WelfareEnterprise welfareEnterprise = welfareEnterpriseService.selectByPrimaryKey(sysAdmin.getEnterpriseId());
        if(EmptyUtils.isNotEmpty(welfareEnterprise)){
            result.put("enterpriseName",EmptyUtils.isNotEmpty(welfareEnterprise.getEnterpriseAbbreviation())?welfareEnterprise.getEnterpriseAbbreviation():welfareEnterprise.getEnterpriseName());
            result.put("enterpriseId",welfareEnterprise.getId());
        }else{
            result.put("enterpriseName","企业福利系统");
            result.put("enterpriseId",0);
        }
        return result;
    }

    @Override
    public String loginVerifyPassword(SysAdmin sysAdmin, String password) {
        //若密码为空则注册密码
        if(EmptyUtils.isEmpty(sysAdmin.getPassword())) {
            sysAdmin.setPassword(PasswordUtil.AESEncrypt(password));
            sysAdmin.setUpdateTime(new Date());
            sysAdminMapper.updateByPrimaryKeySelective(sysAdmin);
        }else{
            if(!PasswordUtil.AESEncrypt(password).equals(sysAdmin.getPassword())) {
                throw new CommonException("账号或密码错误");
            }
        }
        LoginSysAdminVo loginSysAdminVo = new LoginSysAdminVo();
        BeanUtils.copyProperties(sysAdmin,loginSysAdminVo);
        WelfareEnterprise welfareEnterprise = welfareEnterpriseService.selectByPrimaryKey(sysAdmin.getEnterpriseId());
        if(EmptyUtils.isNotEmpty(welfareEnterprise)){
            loginSysAdminVo.setEnterpriseName(EmptyUtils.isNotEmpty(welfareEnterprise.getEnterpriseAbbreviation())?welfareEnterprise.getEnterpriseAbbreviation():welfareEnterprise.getEnterpriseName());
            /*if(welfareEnterprise.getId().equals(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID)){
                welfareEnterprise.setAppRuleConfig(CommonConstants.APP_RULE_CONFIG.SYNC_PLAFORM);
            }*/
            loginSysAdminVo.setAppRuleConfig(EmptyUtils.isEmpty(welfareEnterprise.getAppRuleConfig())?CommonConstants.APP_RULE_CONFIG.SYNC_PLAFORM:welfareEnterprise.getAppRuleConfig());
        }
        List<String> permissions = new ArrayList<>(); //后期动态查
        loginSysAdminVo.setPermissions(permissions);
        String token= TokenUtil.generateToken(sysAdmin.getId());
        //删除之前的登录token
        Object oldToken=RedisUtil.get("companyuser:"+sysAdmin.getId());
        if(EmptyUtils.isNotEmpty(oldToken)){
            RedisUtil.delete(oldToken.toString());
        }
        //保存token到redis
        RedisUtil.set(token, JSON.toJSONString(loginSysAdminVo) ,60*60*24*3);//缓存3天
        //保存用户最新token到redis //缓存7天
        RedisUtil.set("companyuser:"+sysAdmin.getId(), token ,60*60*24*3);
        return token;
    }

    @Override
    public String supplierLoginVerify(WelfareSupplier welfareSupplier, String phone, String password) {
        String correctPwd = welfareSupplier.getPassword();
        if (EmptyUtils.isEmpty(correctPwd)) {
            throw new CommonException("账号或密码错误");
        }
        if (!PasswordUtil.AESDecrypt(correctPwd).equals(password)) {
            throw new CommonException("账号或密码错误");
        }
        WelfareSupplierLoginVo supplierLoginVo = new WelfareSupplierLoginVo();
        BeanUtils.copyProperties(welfareSupplier, supplierLoginVo);
        List<String> permissions = new ArrayList<>(); //后期动态查
        supplierLoginVo.setPermissions(permissions);
        String token= TokenUtil.generateToken(welfareSupplier.getId());
        //删除之前的登录token
        Object oldToken=RedisUtil.get("supplieruser:"+welfareSupplier.getId());
        if(EmptyUtils.isNotEmpty(oldToken)){
            RedisUtil.delete(oldToken.toString());
        }
        //保存token到redis
        RedisUtil.set(token, JSON.toJSONString(supplierLoginVo) ,60*60*24*3);//缓存3天
        //保存用户最新token到redis //缓存7天
        RedisUtil.set("supplieruser:"+welfareSupplier.getId(), token ,60*60*24*3);
        return token;
    }

    @Override
    public Integer saveAdmin(SysAdmin sysAdmin) {
        Integer countUserName = sysAdminMapper.selectSysAdminCount(sysAdmin);
        if(countUserName > 0) {
            throw new CommonException("账号已存在，请重新输入！");
        }
        if(EmptyUtils.isNotEmpty(sysAdmin.getPassword())){
            sysAdmin.setPassword(PasswordUtil.AESEncrypt(sysAdmin.getPassword()));
        }
        //如果是服务端添加或修改企业[主]账号，则该企业下的其他账号变更为非主账号
        if(EmptyUtils.isNotEmpty(sysAdmin.getIsAdmin()) && sysAdmin.getIsAdmin().equals(CommonConstants.YES)){
            sysAdminMapper.updateSysAdminToOrdinaryByEnterpriseId(sysAdmin.getEnterpriseId(),sysAdmin.getType());
        }
        if(EmptyUtils.isEmpty(sysAdmin.getId())) {
            //新增用户
            sysAdmin.setUserStatus(CommonConstants.YES);
            sysAdmin.setCreateTime(new Date());
            sysAdmin.setUpdateTime(new Date());
            //如果是服务端添加企业主账号，则初始化默认角色和菜单信息
            if(EmptyUtils.isNotEmpty(sysAdmin.getIsAdmin()) && sysAdmin.getIsAdmin().equals(CommonConstants.YES)){
                //初始化cms和系统的管理权限
                SysRole role = new SysRole();
                role.setEnterpriseId(sysAdmin.getEnterpriseId());
                role.setName("超级管理员");
                role.setCreateTime(new Date());
                role.setUpdateTime(new Date());
                role.setCreater(sysAdmin.getCreater());
                role.setUpdater(sysAdmin.getUpdater());
                role.setStatus(CommonConstants.YES);
                sysRoleService.insertSelective(role);
                //添加默认菜单并关联到默认角色
               // addDefaultMenuAndRelRole(sysAdmin.getEnterpriseId(),role.getId(),sysAdmin.getCreater());
                List<SysMenu> menuList = sysMenuService.queryAllMenu();
                //添加菜单角色关联
                ArrayList<SysRoleMenu> roleMenuList = new ArrayList<>();
                menuList.forEach(menu->{
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setMenuId(menu.getId());
                    sysRoleMenu.setRoleId(role.getId());
                    sysRoleMenu.setCreateTime(new Date());
                    sysRoleMenu.setUpdateTime(new Date());
                    roleMenuList.add(sysRoleMenu);
                });
                sysRoleMenuService.insertList(roleMenuList);

                //设置用户默认角色id
                sysAdmin.setRoleId(role.getId());
            }
            return sysAdminMapper.insertSelective(sysAdmin);
        } else {
            //修改
            sysAdmin.setUpdateTime(new Date());
            return sysAdminMapper.updateByPrimaryKeySelective(sysAdmin);
        }
    }

    @Override
    public Integer selectIsExists(SysAdmin sysAdmin) {
        return sysAdminMapper.selectSysAdminCount(sysAdmin);
    }

    @Override
    public PageInfo<SysAdminVo> selectSysAdminListPage(SysAdminQuery query) {
        PageHelper.startPage(query);
        List<SysAdminVo> sysAdminVoList = sysAdminMapper.selectSysAdminListPage(query);
        if(EmptyUtils.isNotEmpty(sysAdminVoList)) {
            sysAdminVoList.forEach(entity -> {
                entity.setPassword(PasswordUtil.AESDecrypt(entity.getPassword()));
            });
        }
        PageInfo<SysAdminVo> page = new PageInfo<SysAdminVo>(sysAdminVoList);
        return page;
    }


}
